import React, { Fragment } from 'react'
import { View, StyleSheet, Text, FlatList, LayoutAnimation } from 'react-native'
import { connect } from 'react-redux'
import BasePage from 'src/pageP/base/base-page/index'
import CustomButton from 'src/components/button/CustomButton'
import {
  ScaleS,
  ScaleT,
  ONE_PIXEL,
  NAVIGATIONBAR_HEIGHT,
  HEIGHT
} from 'src/utils/ScreenUtil'
import CheckDeleteView from 'src/components/check-delete-view/index'
import CustomImage from 'src/components/image/CustomImage'
import { openCamera, multipleAlums } from 'src/utils/ImagePickerUtil'
import { isArrayFn } from 'src/utils/JSTypeUtil'
import { ImageViewer } from 'react-native-image-zoom-viewer'
import CustomStatusBar from 'src/components/header/CustomStatusBar'
import { showSelectModal, showModal, showTipModal } from 'src/utils/ModalUtil'
import { updateCompanyInfo, uploadImage } from 'src/utils/RequestAPI'
import { CommonToast } from 'src/utils/ToastUtil'
import { ImageHost } from '../../../config/index'
import { DismissLoading, ShowLoading } from '../../../utils/ToastUtil'
import { fixImageUrl } from 'src/utils/ConfigUtil'

@connect(({ CMineCenterStore, userinfo }) => ({
  userArchiveImgModels: CMineCenterStore.userArchiveImgModels,
  userinfoC: userinfo.C
}))
class CompanyAlbums extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      canEdit: true,
      isManagering: true,
      showImageViewer: false,
      dataSource: [],
      initIndex: 0
    }
    this.selectModalConfig = {
      selectArr: [
        {
          label: '相册上传'
        },
        {
          label: '拍照上传'
        }],
      titleText: '添加照片',
      onCancel: this._selectModalCancel,
      selectClick: this._selectModalClick
    }
    this.config = {
      titleLabel: '提醒',
      contentText: '确定要删除所选照片吗？',
      onCancel: this.onTipCancel,
      onConfirm: this.onTipConfirm
    }
  }

  componentDidMount () {
    const { navigation: { state: { params: { companyPicUrl = [], canEdit = true } = {} } } } = this.props

    const dataSource = companyPicUrl.map((url) => ({
      isSelected: false,
      url
    }))

    this.setState({
      canEdit,
      dataSource
    })
  }

  _selectModalClick = index => {
    switch (index) {
      case 0:
        this.selectModal.close(() => {
          const maxFiles = 9 - (this.state.dataSource || []).length
          multipleAlums({ maxFiles }).then((images) => {
            this._addImage(images)
          })
        })
        break
      case 1:
        this.selectModal.close(() => {
          openCamera({
            width: 750, height: 750
          }).then((image) => {
            console.info(image)
            this._addImage(image)
          })
        })
        break
      default:
        this.selectModal.close()
    }
  }

  _addImage = (img) => {
    if (isArrayFn(img)) {
      this._uploadImages(img)
    } else {
      this._uploadImages([img])
    }
  }

  generator = function * (images) {
    for (let i = 0; i < images.length; i++) {
      yield uploadImage({ params: { uri: images[i].imgPath, type: 'profile', mime: images[i].mime } })
    }
  }

  _uploadImages = (images) => {
    ShowLoading()
    const iterator = this.generator(images)
    const userArchiveImgModels = []

    function handle (iteratorResult) {
      if (iteratorResult.done) {
        console.info(userArchiveImgModels)
        if (userArchiveImgModels.length > 0) {
          this._uploadImage(userArchiveImgModels)
        } else {
          DismissLoading()
        }
        return
      }
      const iteratorValue = iteratorResult.value
      if (iteratorValue instanceof Promise) {
        iteratorValue.then((res) => {
          userArchiveImgModels.push(res.data)
          handle.call(this, iterator.next())
        }).catch(() => {
          handle.call(this, iterator.next())
        })
      }
    }

    handle.call(this, iterator.next())
  }

  _uploadImage = (userArchiveImgModels = []) => {
    const { navigation: { state: { params } } } = this.props
    const oldArrs = this.state.dataSource.map(item => item.url)
    const newArrs = [...userArchiveImgModels, ...oldArrs]
    updateCompanyInfo({
      params: {
        companyId: params.companyId,
        companyPicUrl: newArrs.join(',')
      }
    }).then((data) => {
      // console.info(data)
      // CommonToast(`${userArchiveImgModels.length}张图片上传成功`)
      const dataSource = newArrs.map(url => (
        {
          isSelected: false,
          url
        }
      ))
      this.setState({
        dataSource
      })
      DismissLoading()
    }).catch((data) => {
      DismissLoading()
      console.info(data)
    })
  }

  _renderNavigation () {
    const { canEdit, isManagering, dataSource } = this.state
    let titleText = ''
    if (canEdit && !isManagering) {
      const length = dataSource.filter(e => e.isSelected).length
      if (length) {
        titleText = `已选择${length}张`
      } else {
        titleText = '管理相册'
      }
    }
    return (
      <Fragment>
        <CustomStatusBar />
        <View style={styles.headerView}>
          <View style={styles.headerLeftView}>
            <CustomButton style={styles.headerLeftImgView} onPress={this._onHeaderLeft}>
              <CustomImage
                style={styles.headerLeftImg}
                source={isManagering ? require('@/imgC/home/btnBack.png') : require('@/imgC/userinfo/close_black2.png')} />
            </CustomButton>
          </View>
          <View style={styles.headerCenterView}>
            <Text style={styles.headerCenterText}>{titleText}</Text>
          </View>
          <View style={styles.headerRightView}>
            {
              canEdit && isManagering ? (
                <CustomButton style={styles.managerView} onPress={this.changeManager}>
                  <Text style={styles.managerText}>{'管理'}</Text>
                </CustomButton>
              ) : null
            }
          </View>
        </View>
      </Fragment>
    )
  }

  _onHeaderLeft = () => {
    const { isManagering } = this.state
    const { navigation } = this.props
    if (isManagering) {
      navigation.goBack()
    } else {
      this.setState({
        isManagering: !isManagering
      })
    }
  }

  changeManager = () => {
    const { isManagering } = this.state
    this.setState({
      isManagering: !isManagering
    })
  }

  childRender () {
    const {
      canEdit, isManagering, dataSource
    } = this.state
    const selectAll = dataSource.every(e => e.isSelected)
    const selectSome = selectAll || dataSource.some(e => e.isSelected)
    return (
      <View style={styles.container}>
        {this._renderNavigation()}
        <Text style={styles.titleText}>我的相册</Text>
        {
          canEdit && isManagering ? (
            <CustomButton style={styles.uploadImgView} onPress={this._uploadImgClick}>
              <CustomImage style={styles.uploadImg} source={require('@/imgC/userinfo/add_black.png')} />
              <Text style={styles.uploadText}>上传照片</Text>
            </CustomButton>
          ) : null
        }
        <FlatList
          style={styles.flatList}
          data={dataSource}
          horizontal={false}
          numColumns={3}
          renderItem={this._renderItem}
          keyExtractor={this._keyExtractor}
          extraData={isManagering} />
        {
          !isManagering && (
            <Fragment>
              <View style={styles.line} />
              <CheckDeleteView
                checked={selectAll}
                highlight={selectSome}
                onCheckedPress={this.selectAllClick}
                onDeletePress={this.onDeleteClick} />
            </Fragment>
          )
        }
      </View>
    )
  }

  _uploadImgClick = () => {
    if ((this.state.dataSource).length >= 9) {
      CommonToast('最多只能上传九张')
    } else {
      this._toggleSelectModal(true)
    }
  }

  _toggleSelectModal = (selectModalShow, callBack) => {
    if (selectModalShow) {
      this.selectModal = showSelectModal(this.selectModalConfig)
    } else {
      if (this.selectModal) {
        this.selectModal.close(() => {
          callBack && callBack()
        })
      }
    }
  }

  _selectModalCancel = () => {
    this._toggleSelectModal(false)
  }

  _renderImageViewerHeader = (currentIndex) => {
    const { dataSource } = this.state
    return (
      <View style={styles.imageViewerHeaderView}>
        <View style={styles.imageViewerHeader}>
          <View style={styles.imageViewerLeftView}>
            <CustomButton style={styles.imageViewerLeftImgView} onPress={this._closeImageViewerModal}>
              <CustomImage style={styles.imageViewerLeftImg} source={require('src/imgC/userinfo/close_black2.png')} />
            </CustomButton>
          </View>
          <View style={styles.imageViewerCenterView}>
            <Text style={styles.imageViewerCenter}>{(currentIndex + 1) + '/' + dataSource.length}</Text>
          </View>
          <View style={styles.imageViewerRightView}>
            {
              false && (
                <CustomButton
                  style={styles.imageViewerRightTextView}
                  params={currentIndex}
                  onPress={this._deleteCurrentImg}>
                  <Text style={styles.imageViewerRightText}>删除</Text>
                </CustomButton>
              )
            }
          </View>
        </View>
      </View>
    )
  }

  _renderIndicator = () => {
    return null
  }

  _keyExtractor = item => item.url

  _renderItem = ({ item, index }) => {
    return (
      <CustomButton style={styles.itemView} onPress={this._imgItemClick} params={{ item, index }}>
        <CustomImage style={styles.itemImg} source={{ uri: item.url }} />
        {
          (item.isSelected && !this.state.isManagering) && (
            <View style={styles.itemCloseView}>
              <CustomImage style={styles.itemCloseImg} source={require('@/imgC/userinfo/icon_white_ok.png')} />
            </View>
          )
        }
      </CustomButton>
    )
  }

  _imgItemClick = ({ item, index }) => {
    const { isManagering, dataSource } = this.state
    if (isManagering) {
      this.setState({
        initIndex: index
      }, () => {
        this._showImageViewer()
      })
    } else {
      const newDataSOurce = dataSource.map((e, i) => {
        if (i === index) {
          return {
            ...e,
            isSelected: !e.isSelected
          }
        } else {
          return e
        }
      })
      this.setState({
        dataSource: newDataSOurce
      })
    }
  }

  _imageViewerRef = (imageViewerRef) => {
    this.imageViewerRef = imageViewerRef
  }

  _renderImageViewer = () => {
    const { dataSource, initIndex } = this.state
    return (
      <View style={{ width: '100%', height: HEIGHT }}>
        <ImageViewer
          ref={this._imageViewerRef}
          imageUrls={fixImageUrl(dataSource)}
          enableSwipeDown={false}
          index={initIndex}
          renderHeader={this._renderImageViewerHeader}
          swipeDownThreshold={ScaleS(20)}
          renderIndicator={this._renderIndicator}
        />
      </View>

    )
  }

  _showImageViewer = () => {
    this.imgageViewerModal = showModal(this._renderImageViewer(), 'transparent')
  }

  _closeImageViewerModal = () => {
    if (this.imgageViewerModal) {
      this.imgageViewerModal.close()
    }
  }

  selectAllClick = ({ checked }) => {
    const { dataSource } = this.state
    let newDataSource
    if (checked) {
      // 取消全选
      newDataSource = dataSource.map(e => {
        if (e.isSelected) {
          return {
            ...e,
            isSelected: false
          }
        } else {
          return e
        }
      })
    } else {
      newDataSource = dataSource.map(e => {
        if (!e.isSelected) {
          return {
            ...e,
            isSelected: true
          }
        } else {
          return e
        }
      })
    }

    this.setState({
      dataSource: newDataSource
    })
  }

  onDeleteClick = () => {
    const { dataSource } = this.state
    if (dataSource.some(e => e.isSelected)) {
      this._toggleTipModal(true)
    }
  }

  onTipCancel = () => {
    this._toggleTipModal(false)
  }

  // 删除确认提示
  onTipConfirm = () => {
    const { dataSource } = this.state
    const { navigation: { state: { params } } } = this.props
    const list = dataSource.reduce((allDataArr, currentValue) => {
      return !currentValue.isSelected ? allDataArr.concat(currentValue.url) : allDataArr
    }, [])
    this._toggleTipModal(false, () => {
      updateCompanyInfo({
        params: {
          companyId: params.companyId,
          companyPicUrl: list.join(',')
        }
      }).then(() => {
        CommonToast('照片删除成功')
        this.setState({
          dataSource: dataSource.filter(e => !e.isSelected),
          isManagering: true
        })
      })
    })
  }

  componentWillUnmount () {
    super.componentWillUnmount()
    this.props.navigation.state.params.getMyCompanyBaseInfo()
  }

  _toggleTipModal = (tipModalShow, callBack) => {
    if (tipModalShow) {
      this.tipModal = showTipModal(this.config)
    } else {
      if (this.tipModal) {
        this.tipModal.close(() => {
          callBack && callBack()
        })
      }
    }
  }
}

export default CompanyAlbums

const
  styles = StyleSheet.create({
    container: {
      flex: 1
    },
    headerView: {
      height: ScaleS(44),
      flexDirection: 'row',
      alignItems: 'center'
    },
    headerLeftView: {
      flex: 1
    },
    headerLeftImg: {
      width: ScaleS(19),
      height: ScaleS(13)
    },
    headerLeftImgView: {
      paddingHorizontal: ScaleS(20)
    },
    headerCenterView: {
      flex: 2,
      alignItems: 'center'
    },
    headerCenterText: {
      color: '#030303',
      fontSize: ScaleT(17),
      fontWeight: '400'
    },
    headerRightView: {
      flex: 1,
      alignItems: 'flex-end',
      paddingRight: ScaleS(20)
    },
    managerView: {
      width: ScaleS(58),
      height: ScaleS(28),
      borderRadius: ScaleS(14),
      alignItems: 'center',
      justifyContent: 'center',
      borderColor: '#000000',
      borderWidth: ScaleS(1),
      borderStyle: 'solid'
    },
    managerText: {
      color: '#000000',
      fontSize: ScaleT(12),
      fontWeight: '600'
    },
    uploadImgView: {
      height: ScaleS(47),
      alignItems: 'center',
      flexDirection: 'row',
      paddingHorizontal: ScaleS(20),
      backgroundColor: '#F7F7F7',
      borderRadius: ScaleS(5),
      marginHorizontal: ScaleS(20),
      marginBottom: ScaleS(26)
    },
    uploadImg: {
      width: ScaleS(14),
      height: ScaleS(14)
    },
    uploadText: {
      color: '#000000',
      fontSize: ScaleT(14),
      fontWeight: '400',
      marginLeft: ScaleS(9)
    },
    line: {
      height: ONE_PIXEL,
      backgroundColor: '#EFEFEF'
    },
    titleText: {
      color: '#444444',
      fontSize: ScaleT(25),
      fontWeight: '600',
      marginTop: ScaleS(30),
      marginLeft: ScaleS(20),
      marginBottom: ScaleS(30)
    },
    imageViewerHeaderView: {
      height: NAVIGATIONBAR_HEIGHT,
      backgroundColor: 'white'
    },
    imageViewerHeader: {
      position: 'absolute',
      bottom: 0,
      left: 0,
      right: 0,
      height: ScaleS(44),
      alignItems: 'center',
      flexDirection: 'row'
    },
    imageViewerLeftView: {
      flex: 1,
      alignItems: 'flex-start'
    },
    imageViewerLeftImgView: {
      paddingHorizontal: ScaleS(24),
      height: ScaleS(44),
      alignItems: 'center',
      justifyContent: 'center'
    },
    imageViewerLeftImg: {
      width: ScaleS(15),
      height: ScaleS(15)
    },
    imageViewerCenterView: {
      flex: 1,
      alignItems: 'center'
    },
    imageViewerCenter: {
      color: '#000000',
      fontSize: ScaleT(16),
      fontWeight: '400'
    },
    imageViewerRightView: {
      flex: 1,
      alignItems: 'flex-end'
    },
    flatList: {
      flex: 1,
      marginHorizontal: ScaleS(20)
    },
    itemView: {
      width: ScaleS(112),
      height: ScaleS(112),
      alignItems: 'center',
      position: 'relative'
    },
    itemImg: {
      width: ScaleS(111),
      height: ScaleS(111),
      resizeMode: 'cover',
      borderRadius: ScaleS(4)
    },
    itemCloseView: {
      width: ScaleS(20),
      height: ScaleS(20),
      backgroundColor: '#000000',
      borderRadius: ScaleS(10),
      justifyContent: 'center',
      alignItems: 'center',
      position: 'absolute',
      top: ScaleS(6),
      right: ScaleS(6)
    },
    itemCloseImg: {
      width: ScaleS(12),
      height: ScaleS(8)
    }
  })
